<!-- eslint-disable max-depth -->
<template>
  <!-- <div class="home-page"> -->
  <user-center />
  <operate />
  
  <left-side-bar />
  <content-table
    v-if="firstCatalogList.length"
    @download="download"
  />
  <content-empty v-else />
  <content-footer />
  <content-util @download="download" />
  <!-- </div> -->
</template>

<script lang="ts" setup>
import useSetWindowDragSize from '@/hooks/use-set-window-drag-size'
import { getFirstCatalog } from '@/api/index'
import { onMounted } from 'vue'
import { invokeAsyncAPi, registerInformApi } from '@/utils/xz-fn'
import { useFirstCatalogData } from '@/stores/first-catalog-data'
import { useDownloadPath } from '@/stores/download-path'
import { useUserInfo } from '@/stores/user-info'
import { useDownloadManage } from '@/stores/download-manage'
import { useDownloadManageWindow } from '@/stores/download-manage-window'
import { downloadFinishDB, downingListDB } from '@/db/downloadManage'
import { useConfigData } from '@/stores/config-data'
import { storeToRefs } from 'pinia'
import useDialogPromiseHook from '@/hooks/use-dialog-promise-hook'
import { useFakeDownload } from '@/stores/fake-download'
import {useEnvConfig} from '@/config'
const {ENV_CONFIG} = useEnvConfig()
useSetWindowDragSize()

const firstCatalogDataStore = useFirstCatalogData()
const downloadPathStore = useDownloadPath()
const userInfoStore = useUserInfo();
const { isMember } = storeToRefs(userInfoStore)
const { isDefaultPath } = storeToRefs(downloadPathStore)
const {firstCatalogList} =storeToRefs(firstCatalogDataStore)
const downloadManageStore = useDownloadManage()
const downloadManageWindowStore = useDownloadManageWindow()
const configDataStore = useConfigData();
const dialog = useDialogPromiseHook();

const fakeDownloadStore = useFakeDownload();

registerInformApi('Notify_WebService', (type: string, data: any) => {
  if (type === 'Notify_DownloadProgress') {
    downloadManageStore.processDowningItem(data)
  } else if (type === 'Notify_DownloadResult') {
    downloadManageStore.finishDowningItem(data)
  }
})

registerInformApi('Notify_WebMessage', (windowId: string, type: string, data: any) => {
  if (type === 'get-downing-table-list') {//获取下载中数据
    downloadManageStore.sendDowningDataToManageWindow()
  } else if (type === 'get-download-finish-table-list') {//获取下载完成数据
    downloadManageStore.sendFinishDownloadDataToManageWindow()
  } else if (type === 'get-download-finish-red-flag') {//获取小红点是否标注
    downloadManageStore.sendFinishDownloadRedFlagToManageWindow()
  } else if (type==='get-download-is-member') {
    userInfoStore.sendIsMemberToManageWindow();
  } else if (type === 'start-downing-table-list') {//恢复下载
    downloadManageStore.startItem(data.id)
  } else if (type === 'stop-downing-table-list') {//暂停下载
    downloadManageStore.stopItem(data.id,false)
  } else if (type === 'delete-downing-table-list') {//删除下载中的item
    downloadManageStore.deleteDowningListItem( data.id)
  }else if (type === 'delete-down-finish-table-list') {//删除下载完成的item
    downloadManageStore.deleteDownloadFinishItem(data.id)
  } else if (type === 'stop-all-downing-table-list') {//暂停所有
    downloadManageStore.stopAllDowningListItem();
  } else if (type === 'run-all-downing-table-list') {//启动所有
    downloadManageStore.startAllDowningListItem();
  } else if (type === 'delete-all-downing-table-list') {//删除所有
    downloadManageStore.deleteAllDowningListItem();
  } else if (type === 'delete-all-finish-download-table-list') {//删除所有的完成的记录
    downloadManageStore.deleteAllFinishDownloadListItem();
  } else if (type === 'close-download-manage-window') {//子窗口关闭
    downloadManageWindowStore.setDownloadManageWindowId('');
  } else if (type === 'close-download-finish-window') {
    downloadManageWindowStore.setDownloadFinishWindowId('');
  } else if (type === 'close-user-overload-window') {
    downloadManageWindowStore.setUserOverLoadWindowId('');
  } else if (type === 'close-fake-download-dialog') {
    fakeDownloadStore.setShowDialog(false);
  } else if (type === 'open-download-manage') {//下载完成页面，吊起下载管理页面
    downloadManageWindowStore.openDownloadManageWindow('2');
  } else if (type === 'reset-download-finish-red-flag') {//清除下载完成小红点
    downloadManageStore.resetDownloadFinishRedFlag();
  } else if (type === 'continue-user-overload-dialog') {
    downloadManageStore.startItem(data);
  } else if (type === 'change-member-state') {
    userInfoStore.setIsMember(true);
    downloadManageStore.memberStatusChange();
  }
})


const getCatalogData = async () => {//获取分类信息
  const { code, data } = await getFirstCatalog()

  if (code === 200) {

    let showTable: any = {}
    let tableAttribute: any = {};
    let sign_type: string = '';

    try {
      showTable = JSON.parse(data.first_category[0].attributes).showTable
      tableAttribute = JSON.parse(data.first_category[0].attributes).attributes
      sign_type= JSON.parse(data.first_category[0].attributes).signType
    } catch (ex) {
      showTable = {}
      tableAttribute = {}
      sign_type=''
    }

    const table_column = []

    for (const key in showTable) {
      table_column.push({
        title: key,
        sign_type,
        ...showTable[key]
      })
    }

    firstCatalogDataStore.setFirstCatalogTable(table_column)
    firstCatalogDataStore.setFirstCatalogTableAttribute(tableAttribute)
    firstCatalogDataStore.setFirstCatalogId(data.first_category[0].id)
    firstCatalogDataStore.setFirstCatalogList(data.first_category[0].categories)
  }
}

const initDownloadPath = async () => {
  //初始化本地的下载路径信息

  const downloadPath = localStorage.getItem(`${ENV_CONFIG.DEFAULT_PATH_NAME}_download_path`)
  const downloadPathIsDefault = localStorage.getItem(`${ENV_CONFIG.DEFAULT_PATH_NAME}_download_path_is_default`)
  const closeAndHide= localStorage.getItem(`${ENV_CONFIG.DEFAULT_PATH_NAME}_close_and_quit`)//
  if (!downloadPath) {
    const rs = await invokeAsyncAPi('fq_GetDiskWithMaxFreeSpace') //获取系统最大磁盘
    if (rs) {
      downloadPathStore.setDownloadPath(rs + ENV_CONFIG.DEFAULT_PATH_NAME)
    }
  } else {
    downloadPathStore.setDownloadPath(downloadPath)
  }
  if (!downloadPathIsDefault) {
    downloadPathStore.setIsDefault(false)
  } else {
    downloadPathStore.setIsDefault(JSON.parse(downloadPathIsDefault))
  }
  if (!closeAndHide) {
    downloadPathStore.setCloseAndHide(true)
  } else {
    downloadPathStore.setCloseAndHide(JSON.parse(closeAndHide))
  }
}

const getMasterWindowId = async () => {
  const id = await  invokeAsyncAPi('jsMsg_GetWndID') //获取系统最大磁盘
  downloadManageWindowStore.setMasterWindowId(id)
}

const getDownloadManageDbData = () => {
  //获取下载管理的db数据
  downloadFinishDB.getAll().then((list: any) => {
    if (list.length) {
      
      const _list: any[] = []
      for (const item of list) {
        _list.push({ ...item })
      }
      downloadManageStore.setFinishList(_list);
    }
  })
  downingListDB.getAll().then((list: any) => {//获取下载中的列表
    if (list.length) {

      const _list: any[] = []
      for (const item of list) {
        const obj = { ...item };
        obj.downloadId = '';
        if (['1', '5'].includes(obj.status)) {
          obj.status = '4';
        }

        obj.needTime = 0
        obj.needTimeStr='-- : -- : --'
        obj.downloadSpeed = 0
        obj.downloadSpeedStr = '0KB'
      
        _list.push(obj)
      }
      downloadManageStore.setDowningList(_list)
    }
  })
}


const getWebPath = async () => {//获取web项目路径，正式需要
  const _path = await invokeAsyncAPi('fq_GetLocalWebResPath')
  configDataStore.setWebPath(_path);
}

onMounted(() => {
  getCatalogData() //获取目录信息
  getDownloadManageDbData() //获取下载管理列表
  initDownloadPath() //获取下载路径设置
  getMasterWindowId() //获取主窗口id
  getWebPath();

    // userOverload
    
})


const startDownload = (item: any) => {
  if (!isDefaultPath.value) {
    dialog.showDialog('download', {
      fileName: item.file_name,
      fileSize:item.size
    }).then(() => {
      downloadManageStore.addToDowningList(item);
    }).catch(() => {
    })
  } else {
    downloadManageStore.addToDowningList(item);
  }
}

const download = (item: any) => {
  if (!isMember.value) {
    if (item._type === 'table' && item._index === 1 && ENV_CONFIG.type === 'warcraft') {//
      invokeAsyncAPi('fq_ShowUserCenter')
      return;
    }
    dialog.showDialog('member').then(() => {
      startDownload(item);
    }).catch((value) => {
      if (value === 'member') {
        invokeAsyncAPi('fq_ShowUserCenter')
      }
    })
  } else {
    startDownload(item);
  }
}

</script>

<style lang="scss" scoped>
// .home-page{
//   background:red;
//   position: relative;
// }
</style>
